const { pool } = require('../config/db');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

// JWT密钥（生产环境应该从环境变量读取）
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production';
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '24h';

/**
 * 用户认证服务
 */
class AuthService {
  /**
   * 用户登录
   * @param {string} username - 用户名
   * @param {string} password - 密码
   * @param {string} ip - 登录IP
   * @returns {Promise<Object>} - 登录结果（包含token和用户信息）
   */
  async login(username, password, ip = null) {
    try {
      // 查询用户
      const [rows] = await pool.execute(
        'SELECT * FROM system_users WHERE username = ? AND status = ?',
        [username, 'active']
      );

      if (rows.length === 0) {
        return {
          success: false,
          message: '用户名或密码错误'
        };
      }

      const user = rows[0];

      // 验证密码
      const isPasswordValid = await bcrypt.compare(password, user.password);
      if (!isPasswordValid) {
        return {
          success: false,
          message: '用户名或密码错误'
        };
      }

      // 更新最后登录时间和IP
      await pool.execute(
        'UPDATE system_users SET last_login_time = NOW(), last_login_ip = ? WHERE id = ?',
        [ip, user.id]
      );

      // 生成JWT token
      const token = jwt.sign(
        {
          userId: user.id,
          username: user.username,
          realName: user.real_name,
          employeeId: user.employee_id,
          role: user.role
        },
        JWT_SECRET,
        { expiresIn: JWT_EXPIRES_IN }
      );

      // 返回用户信息（不包含密码）
      const userInfo = {
        id: user.id,
        username: user.username,
        realName: user.real_name,
        employeeId: user.employee_id,
        email: user.email,
        phone: user.phone,
        role: user.role
      };

      return {
        success: true,
        message: '登录成功',
        token,
        user: userInfo
      };
    } catch (error) {
      console.error('登录失败:', error.message);
      throw error;
    }
  }

  /**
   * 验证token
   * @param {string} token - JWT token
   * @returns {Object|null} - 解码后的用户信息或null
   */
  verifyToken(token) {
    try {
      const decoded = jwt.verify(token, JWT_SECRET);
      return decoded;
    } catch (error) {
      console.error('Token验证失败:', error.message);
      return null;
    }
  }

  /**
   * 根据用户ID获取用户信息
   * @param {number} userId - 用户ID
   * @returns {Promise<Object>} - 用户信息
   */
  async getUserById(userId) {
    try {
      const [rows] = await pool.execute(
        'SELECT id, username, real_name, employee_id, email, phone, role, status FROM system_users WHERE id = ?',
        [userId]
      );

      if (rows.length === 0) {
        return null;
      }

      return {
        id: rows[0].id,
        username: rows[0].username,
        realName: rows[0].real_name,
        employeeId: rows[0].employee_id,
        email: rows[0].email,
        phone: rows[0].phone,
        role: rows[0].role,
        status: rows[0].status
      };
    } catch (error) {
      console.error('获取用户信息失败:', error.message);
      throw error;
    }
  }

  /**
   * 创建新用户
   * @param {Object} userData - 用户数据
   * @returns {Promise<Object>} - 创建结果
   */
  async createUser(userData) {
    try {
      const { username, password, realName, employeeId, email, phone, role = 'operator' } = userData;

      // 检查用户名是否已存在
      const [existing] = await pool.execute(
        'SELECT id FROM system_users WHERE username = ?',
        [username]
      );

      if (existing.length > 0) {
        return {
          success: false,
          message: '用户名已存在'
        };
      }

      // 检查工号是否已存在（如果提供了工号）
      if (employeeId && employeeId.trim() !== '') {
        const [existingEmployee] = await pool.execute(
          'SELECT id FROM system_users WHERE employee_id = ?',
          [employeeId]
        );

        if (existingEmployee.length > 0) {
          return {
            success: false,
            message: '工号已存在'
          };
        }
      }

      // 加密密码
      const hashedPassword = await bcrypt.hash(password, 10);

      // 处理空字符串，转为 NULL（避免唯一索引冲突）
      const finalEmployeeId = (employeeId && employeeId.trim() !== '') ? employeeId : null;
      const finalEmail = (email && email.trim() !== '') ? email : null;
      const finalPhone = (phone && phone.trim() !== '') ? phone : null;

      // 插入用户
      const [result] = await pool.execute(
        `INSERT INTO system_users (username, password, real_name, employee_id, email, phone, role) 
         VALUES (?, ?, ?, ?, ?, ?, ?)`,
        [username, hashedPassword, realName, finalEmployeeId, finalEmail, finalPhone, role]
      );

      return {
        success: true,
        message: '用户创建成功',
        userId: result.insertId
      };
    } catch (error) {
      console.error('创建用户失败:', error.message);
      throw error;
    }
  }

  /**
   * 修改密码
   * @param {number} userId - 用户ID
   * @param {string} oldPassword - 旧密码
   * @param {string} newPassword - 新密码
   * @returns {Promise<Object>} - 修改结果
   */
  async changePassword(userId, oldPassword, newPassword) {
    try {
      // 查询用户
      const [rows] = await pool.execute(
        'SELECT password FROM system_users WHERE id = ?',
        [userId]
      );

      if (rows.length === 0) {
        return {
          success: false,
          message: '用户不存在'
        };
      }

      // 验证旧密码
      const isValid = await bcrypt.compare(oldPassword, rows[0].password);
      if (!isValid) {
        return {
          success: false,
          message: '原密码错误'
        };
      }

      // 加密新密码
      const hashedPassword = await bcrypt.hash(newPassword, 10);

      // 更新密码
      await pool.execute(
        'UPDATE system_users SET password = ? WHERE id = ?',
        [hashedPassword, userId]
      );

      return {
        success: true,
        message: '密码修改成功'
      };
    } catch (error) {
      console.error('修改密码失败:', error.message);
      throw error;
    }
  }

  /**
   * 获取用户列表
   * @param {number} page - 页码
   * @param {number} pageSize - 每页数量
   * @returns {Promise<Object>} - 用户列表
   */
  async getUserList(page = 1, pageSize = 20) {
    try {
      const offset = (page - 1) * pageSize;

      // 查询总数
      const [countResult] = await pool.execute('SELECT COUNT(*) as total FROM system_users');
      const total = countResult[0].total;

      // 查询数据
      const [rows] = await pool.execute(
        `SELECT id, username, real_name, employee_id, email, phone, role, status, 
                last_login_time, last_login_ip, created_at 
         FROM system_users 
         ORDER BY created_at DESC 
         LIMIT ? OFFSET ?`,
        [pageSize, offset]
      );

      return {
        success: true,
        data: rows.map(row => ({
          id: row.id,
          username: row.username,
          realName: row.real_name,
          employeeId: row.employee_id,
          email: row.email,
          phone: row.phone,
          role: row.role,
          status: row.status,
          lastLoginTime: row.last_login_time,
          lastLoginIp: row.last_login_ip,
          createdAt: row.created_at
        })),
        pagination: {
          page,
          pageSize,
          total,
          totalPages: Math.ceil(total / pageSize)
        }
      };
    } catch (error) {
      console.error('获取用户列表失败:', error.message);
      throw error;
    }
  }

  /**
   * 更新用户信息
   * @param {number} userId - 用户ID
   * @param {Object} userData - 用户数据
   * @returns {Promise<Object>} - 更新结果
   */
  async updateUser(userId, userData) {
    try {
      const { realName, employeeId, role, email, phone, status } = userData;

      // 检查工号是否已被其他用户使用
      if (employeeId && employeeId.trim() !== '') {
        const [existingEmployee] = await pool.execute(
          'SELECT id FROM system_users WHERE employee_id = ? AND id != ?',
          [employeeId, userId]
        );

        if (existingEmployee.length > 0) {
          return {
            success: false,
            message: '工号已被其他用户使用'
          };
        }
      }

      // 处理空字符串，转为 NULL
      const finalEmployeeId = (employeeId && employeeId.trim() !== '') ? employeeId : null;
      const finalEmail = (email && email.trim() !== '') ? email : null;
      const finalPhone = (phone && phone.trim() !== '') ? phone : null;

      await pool.execute(
        `UPDATE system_users 
         SET real_name = ?, employee_id = ?, role = ?, email = ?, phone = ?, status = ?
         WHERE id = ?`,
        [realName, finalEmployeeId, role, finalEmail, finalPhone, status, userId]
      );

      return {
        success: true,
        message: '用户更新成功'
      };
    } catch (error) {
      console.error('更新用户失败:', error.message);
      throw error;
    }
  }

  /**
   * 删除用户
   * @param {number} userId - 用户ID
   * @returns {Promise<Object>} - 删除结果
   */
  async deleteUser(userId) {
    try {
      // 检查是否是admin用户
      const [rows] = await pool.execute(
        'SELECT username FROM system_users WHERE id = ?',
        [userId]
      );

      if (rows.length === 0) {
        return {
          success: false,
          message: '用户不存在'
        };
      }

      if (rows[0].username === 'admin') {
        return {
          success: false,
          message: '不能删除默认管理员账号'
        };
      }

      await pool.execute('DELETE FROM system_users WHERE id = ?', [userId]);

      return {
        success: true,
        message: '用户删除成功'
      };
    } catch (error) {
      console.error('删除用户失败:', error.message);
      throw error;
    }
  }

  /**
   * 重置用户密码（管理员操作）
   * @param {number} userId - 用户ID
   * @param {string} newPassword - 新密码
   * @returns {Promise<Object>} - 重置结果
   */
  async resetUserPassword(userId, newPassword) {
    try {
      // 加密新密码
      const hashedPassword = await bcrypt.hash(newPassword, 10);

      // 更新密码
      await pool.execute(
        'UPDATE system_users SET password = ? WHERE id = ?',
        [hashedPassword, userId]
      );

      return {
        success: true,
        message: '密码重置成功'
      };
    } catch (error) {
      console.error('重置密码失败:', error.message);
      throw error;
    }
  }
}

module.exports = new AuthService();

